package com.xisoft.devise.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.xisoft.common.*;
import com.xisoft.common.bean.BeanHelper;
import com.xisoft.common.constant.IPubCons;
import com.xisoft.common.io.FileUtilbc;
import com.xisoft.common.pubEnv.*;
import com.xisoft.devise.config.template.GeneratorConfig;
import com.xisoft.devise.config.template.GeneratorInfo;
import com.xisoft.devise.entity.*;
import com.xisoft.devise.mapper.IMetadataMapper;
import com.xisoft.devise.service.EngineService;
import com.xisoft.devise.utils.GenUtils;
import com.xisoft.utils.SpringHelper;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * *
 * Created with Description:
 *
 * @version 1.0 <br>
 * @packagename: com.xisoft.frame.service<br>
 * @author: LiBencheng <br>
 * @computer: licheng <br>
 * @date: Created on 2022/9/7 10:10 <br>
 */
@Service ("EngineServiceImpl")
public class EngineServiceImpl implements EngineService
{
    StringBuffer javaStr = new StringBuffer();

    @Autowired
    private IMetadataMapper mapper;

    /************************************************************* <br>
     *
     *说明: 生成配置信息<br>
     *
     * @Description   <br>
     * @Date Created on 2022/9/7  15:07  <br>
     * @return java.lang.String  <br>
     * @Author LIBENCHENG
     * @version 1.0 <br>
     ************************************************************* <br>
     */
    @Override public String generateConfig(String json) throws Exception
    {
        // json = "{moduleType: config,code: queryHrArrearsRules}";
        // json = "{moduleType: form,code: hrSalaryTaxationForm,hrSalaryArrearsRules}";
        // json = "{moduleType: list,code: hrSalaryArrearsRulesBusiness,hrSalaryArrearsRulesList,hrSalaryDataList}";
        // json = "{moduleType: tree,code:hrSalaryArrearsRulesList}";
        // json = "{moduleType: tabs,code:hrSalaryArrearsRulesList}";
        // json = "{moduleType: layout,code:hrSalaryArrearsRulesList}";
        // json = "{moduleType: form,code:SQ01Form_XZH}";
        // json = "{moduleType: list,code:\"bxCostApplyEmpList,appBxsqCostDetailList,BxsqYSCostDetailList," +
        //         "costDetailList,appBxsqZxCostDetailList\"}";

        // json = "{moduleType: config,code: queryHrArrexrsRules,queryHrArrearsRulesBusiness}";  // 执行配置
        // json = "{moduleType: list,code: hrSalaryArrearsRulesBusiness,hrSalaryArrearsRulesList}"; // 列表
        // json = "{moduleType: form,code: hrSalaryArrearsRules}"; //表单
        // json = "{moduleType: form,code: SQ01Form_YZ}"; //表单
        // json = "{moduleType: list,code: BxCostApplyList}"; // 列表
        // json = "{moduleType: config,code: queryBxBillListByCuser}";  // 执行配置

        // json = "{moduleType: list,moduleCode:bx,code: BxRefundAccountMeangementList}"; // 列表

        Map< String,Object > param = JsonUtil.toMap(json);
        StringBuffer msg = new StringBuffer();
        // 旧版-拼接Java代码
        // GenerateJava genJava = new GenerateJava();
        // 新版-模板生成Java代码
        GenTemplateJava genJava = new GenTemplateJava();
        String moduleType = StringUtil.toString(param.get("moduleType"));
        String mdCode = StringUtil.toString(param.get("moduleCode"));
        String[] codes = StringUtil.toString(param.get("code")).split(IPubCons.COMMA);
        for (int i = 0; i < PubEnvUtil.getSize(codes); i++)
        {
            if (PubEnvUtil.isEmpty(codes[i])) { continue; }
            moduleType = moduleType.trim();
            mdCode = mdCode.trim();
            String code = codes[i].trim();
            if (PubEnvUtil.equals("form", moduleType))
            { msg.append(genJava.parseForm(moduleType, mdCode, code)); }
            else if (PubEnvUtil.equals("list", moduleType))
            { msg.append(genJava.parseList(moduleType, mdCode, code)); }
            else if (PubEnvUtil.equals("config", moduleType))
            { msg.append(genJava.parseConfig(moduleType, mdCode, code)); }
            else if (PubEnvUtil.equals("tree", moduleType))
            { msg.append(genJava.parseTree(moduleType, mdCode, code)); }
            else if (PubEnvUtil.equals("tabs", moduleType))
            { msg.append(genJava.parseTabs(moduleType, mdCode, code)); }
            else if (PubEnvUtil.equals("layout", moduleType))
            { msg.append(genJava.parseLayout(moduleType, mdCode, code)); }

        }

        System.out.println(msg);

        return StringUtil.toString(msg);
    }

    class GenTemplateJava
    {
        @Autowired
        private GeneratorConfig generatorConfig;

        public String parseLayout(String moduleType, String mdCode, String code) throws Exception
        {
            StringBuffer classNames = new StringBuffer();
            classNames.append("这个code（").append(code).append("）数据库没有查到对应的数据！");

            String sql = "SELECT * FROM sys_sqlconfig  sff WHERE ccode='" + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            // List< Map > mapList = Db.use().query(sql, Map.class);
            for (Map tempMap : mapList)
            {
                String className = StringUtil.firstCharUpperCase(code);
                String name = StringUtil.valueOfEmpty(tempMap.get("sfl_name"));
                GenEngineModel genModel = getGenModel(className, moduleType, mdCode, name);
                genModel.setAttributes(setValue(tempMap, code, name));
                makeCode(genModel);

                classNames = new StringBuffer();
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }

        public String parseTabs(String moduleType, String mdCode, String code) throws Exception
        {
            StringBuffer classNames = new StringBuffer();
            classNames.append("这个code（").append(code).append("）数据库没有查到对应的数据！");

            String sql = "SELECT * FROM sys_function_tabs WHERE sft_code = ' " + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            // List< Map > mapList = Db.use().query(sql, Map.class);
            for (Map tempMap : mapList)
            {
                String className = StringUtil.firstCharUpperCase(code);
                String name = StringUtil.valueOfEmpty(tempMap.get("sfl_name"));
                GenEngineModel genModel = getGenModel(className, moduleType, mdCode, name);
                genModel.setAttributes(setValue(tempMap, code, name));
                makeCode(genModel);

                classNames = new StringBuffer();
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }

        public String parseTree(String moduleType, String mdCode, String code) throws Exception
        {
            StringBuffer classNames = new StringBuffer();
            classNames.append("这个code（").append(code).append("）数据库没有查到对应的数据！");

            String sql = "SELECT * FROM sys_sqlconfig  sff WHERE ccode='" + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            //   List< Map > mapList = Db.use().query(sql, Map.class);
            for (Map tempMap : mapList)
            {
                String className = StringUtil.firstCharUpperCase(code);
                String name = StringUtil.valueOfEmpty(tempMap.get("sfl_name"));
                GenEngineModel genModel = getGenModel(className, moduleType, mdCode, name);
                genModel.setAttributes(setValue(tempMap, code, name));
                makeCode(genModel);

                classNames = new StringBuffer();
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }

        public String parseConfig(String moduleType, String mdCode, String code) throws Exception
        {
            StringBuffer classNames = new StringBuffer();
            classNames.append("这个code（").append(code).append("）数据库没有查到对应的数据！");

            String sql = "SELECT * FROM sys_sqlconfig  sff WHERE ccode='" + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            // List< Map > mapList = Db.use().query(sql, Map.class);
            for (Map tempMap : mapList)
            {
                String className = StringUtil.firstCharUpperCase(code);
                String name = StringUtil.valueOfEmpty(tempMap.get("sfl_name"));
                GenEngineModel genModel = getGenModel(className, moduleType, mdCode, name);
                genModel.setAttributes(setValue(tempMap, code, name));
                makeCode(genModel);

                classNames = new StringBuffer();
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }

        public String parseList(String moduleType, String mdCode, String code) throws Exception
        {
            StringBuffer classNames = new StringBuffer();
            classNames.append("这个code（").append(code).append("）数据库没有查到对应的数据！");

            String sql = "SELECT * FROM sys_function_list  WHERE  sfl_code = '" + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            // List< Map > mapList = Db.use().query(sql, Map.class);
            for (Map tempMap : mapList)
            {
                String className = StringUtil.firstCharUpperCase(code);
                String name = StringUtil.valueOfEmpty(tempMap.get("sfl_name"));
                GenEngineModel genModel = getGenModel(className, moduleType, mdCode, name);
                genModel.setAttributes(setValue(tempMap, code, name));

                sql = "SELECT * FROM sys_function_list_column WHERE sfl_id= '" + tempMap.get("sfl_id") + "'";
                List< Map > tempList = mapper.getDataBySql(sql);
                genModel.setColumns(setValue(tempList, "columns"));

                sql = "SELECT * FROM sys_function_list_button WHERE sfl_id= '" + tempMap.get("sfl_id") + "'";
                tempList = mapper.getDataBySql(sql);
                genModel.setButtons(setValue(tempList, "buttons"));
                makeCode(genModel);

                classNames = new StringBuffer();
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }

        public String parseForm(String moduleType, String mdCode, String code) throws Exception
        {
            StringBuffer classNames = new StringBuffer();
            classNames.append("这个code（").append(code).append("）数据库没有查到对应的数据！");

            String sql = "SELECT * FROM sys_function_form sff WHERE SFF_CODE='" + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            for (Map tempMap : mapList)
            {
                String className = StringUtil.firstCharUpperCase(code);
                String name = StringUtil.valueOfEmpty(tempMap.get("sfl_name"));
                GenEngineModel genModel = getGenModel(className, moduleType, mdCode, name);
                genModel.setAttributes(setValue(tempMap, code, name));

                sql = "SELECT * FROM sys_function_form_child WHERE SFF_ID= '"
                        + tempMap.get("sff_id") + "' ORDER BY sff_type,sff_index ";
                List< Map > tempList = mapper.getDataBySql(sql);
                genModel.setChildren(setValue(tempList, "children"));
                makeCode(genModel);

                classNames = new StringBuffer();
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }


        /************************************************************* <br>
         *
         *说明: 制作 引擎代码<br>
         *
         * @Description   <br>
         * @Date Created on 2022/9/26  13:57  <br>
         * @param genModel <br>
         * @return void  <br>
         * @Author LIBENCHENG
         * @version 1.0 <br>
         ************************************************************* <br>
         */
        private void makeCode(GenEngineModel genModel) throws Exception
        {
            //代码生成器信息
            GeneratorInfo generator = SpringHelper.getBean(GeneratorConfig.class).getGeneratorConfig();

            //渲染模板并输出
            for (TemplateInfo template : generator.getTemplates())
            {
                if (PubEnvUtil.equals("Engine.java.ftl", template.getTemplateName()))
                {
                    genModel.setTemplateName(template.getTemplateName());
                    Map< String,Object > bean2Map = BeanHelper.transBean2Map(genModel);
                    bean2Map.put("package", genModel.getPackageName());
                    String content = GenUtils.getTemplateContent(template.getTemplateContent(), bean2Map);
                    String path = GenUtils.getTemplateContent(template.getGeneratorPath(), bean2Map);

                    FileUtils.writeStringToFile(new File(path), content, "utf-8");
                    System.out.println("生成代码路径：" + path);
                }
            }
        }

        private GenEngineModel getGenModel(String className, String moduleType, String mdCode, Object engineName) throws Exception
        {
            GenEngineModel genModel = new GenEngineModel();
            genModel.setTableComments("类型/名称 <=> " + moduleType + "/" + engineName);
            //表信息
            genModel.setClassName(className);
            genModel.setSubModuleName("");
            genModel.setInherit("");
            // 定义生成的引擎的父类
            if (PubEnvUtil.equals("list", moduleType))
            { genModel.setInherit("extends com.xisoft.core.product.entity.config.table.Table"); }
            if (PubEnvUtil.equals("form", moduleType))
            { genModel.setInherit("extends com.xisoft.core.product.entity.config.form.Form"); }

            genModel.setConfigType(moduleType);
            if (!PubEnvUtil.isEmpty(mdCode))
            { genModel.setModuleName(mdCode); }
            return genModel;
        }

        /************************************************************* <br>
         *
         *说明: 處理内容<br>
         *
         * @Description   <br>
         * @Date Created on 2022/10/9  14:02  <br>
         * @param configMap <br>
         * @return java.util.List<java.lang.String>  <br>
         * @Author LIBENCHENG
         * @version 1.0 <br>
         ************************************************************* <br>
         */
        public List< String > setValue(Map configMap, String code, String name) throws Exception
        {
            List< String > tempList = new ArrayList<>();
            configMap.put("code", code);
            configMap.put("name", name);
            for (Object obj : configMap.keySet())
            {
                String value = JSONObject.toJSONString(configMap.get(obj)).replace(IPubCons.QUOTE, "'");
                tempList.add("private String " + obj + "= \"" + value + "\";");
            }
            return tempList;
        }

        /************************************************************* <br>
         *
         *说明: 处理子集信息 <br>
         *
         * @Description   <br>
         * @Date Created on 2022/10/9  14:02  <br>
         * @param childList
         * @param initMethod <br>
         * @return java.util.List<java.lang.String>  <br>
         * @Author LIBENCHENG
         * @version 1.0 <br>
         ************************************************************* <br>
         */
        public List< String > setValue(List childList, String initMethod) throws Exception
        {
            List< String > tempList = new ArrayList<>(PubEnvUtil.getSize(childList));
            for (Object obj : childList)
            {
                Map childMap = (Map) obj;
                String value = JSONObject.toJSONString(childMap).replace(IPubCons.QUOTE, "'");
                tempList.add(value);
            }

            return tempList;
        }
    }


    /**
     * *
     * Created with Description:
     *
     * @fileRelativePath: EngineServiceImpl.java
     * @Date: Created on 2022/9/26  13:57  <br>
     * @author: LiBencheng <br>
     * @version: 1.0 <br>
     */
    class GenerateJava
    {
        String getClassPatch( ) throws IOException
        {
            String filePath = this.getClass().getResource("/application.properties").getPath();
            Map< String,String > proMap = PropertiesUtil.getAllProperties(filePath);

            return proMap.get("classpatch");
        }

        public String parseLayout(String moduleType, String code) throws Exception
        {

            StringBuffer classNames = new StringBuffer();
            String sql = "SELECT * FROM sys_sqlconfig  sff WHERE ccode='" + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            // List< Map > mapList = Db.use().query(sql, Map.class);
            for (Map map : mapList)
            {
                javaStr = new StringBuffer();
                String className = StringUtil.firstCharUpperCase(StringUtil.valueOfZero(map.get("ccode")));
                // 處理头部
                parseHead(map, moduleType, className);
                // 处理构造函数
                javaStr.append("    public ").append(className).append("( )").append(IPubCons.CRLF)
                       .append("    {").append(IPubCons.CRLF).append("    }").append(IPubCons.CRLF);
                set("configCode", StringUtil.valueOfZero(map.get("ccode")));
                set("code", StringUtil.valueOfZero(map.get("ccode")));
                // 處理内容
                parseBody(map);
                // 类结束 }
                javaStr.append(" }").append(IPubCons.CRLF);
                // 生成修改表脚本，
                FileUtilbc.write(new File(getClassPatch() + className + IPubCons.DOT_JAVA)
                        , StringUtil.toString(javaStr), PubEnvUtil.UTF_8);
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }

        public String parseTabs(String moduleType, String code) throws Exception
        {

            StringBuffer classNames = new StringBuffer();
            String sql = "SELECT * FROM sys_function_tabs WHERE sft_code = ' " + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            // List< Map > mapList = Db.use().query(sql, Map.class);
            for (Map map : mapList)
            {
                javaStr = new StringBuffer();
                String className = StringUtil.firstCharUpperCase(StringUtil.valueOfZero(map.get("sft_code")));
                // 處理头部
                parseHead(map, moduleType, className);
                // 处理构造函数
                javaStr.append("    public ").append(className).append("( )").append(IPubCons.CRLF)
                       .append("    {").append(IPubCons.CRLF).append("    }").append(IPubCons.CRLF);
                set("configCode", StringUtil.valueOfZero(map.get("sft_code")));
                set("code", StringUtil.valueOfZero(map.get("sft_code")));
                // 處理内容
                parseBody(map);    // 处理子表
                sql = "SELECT * FROM sys_function_tabs_items  WHERE sft_id ='" + map.get("sft_id") + "'";
                List< Map > childList = mapper.getDataBySql(sql);
                // List< Map > childList = Db.use().query(sql, Map.class);
                parseChild(childList, "items");
                // 类结束 }
                javaStr.append(" }").append(IPubCons.CRLF);
                // 生成修改表脚本，
                FileUtilbc.write(new File(getClassPatch() + className + IPubCons.DOT_JAVA)
                        , StringUtil.toString(javaStr), PubEnvUtil.UTF_8);
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }

        public String parseTree(String moduleType, String code) throws Exception
        {

            StringBuffer classNames = new StringBuffer();
            String sql = "SELECT * FROM sys_sqlconfig  sff WHERE ccode='" + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            //   List< Map > mapList = Db.use().query(sql, Map.class);
            for (Map map : mapList)
            {
                javaStr = new StringBuffer();
                String className = StringUtil.firstCharUpperCase(StringUtil.valueOfZero(map.get("ccode")));
                // 處理头部
                parseHead(map, moduleType, className);
                // 处理构造函数
                javaStr.append("    public ").append(className).append("( )").append(IPubCons.CRLF)
                       .append("    {").append(IPubCons.CRLF).append("    }").append(IPubCons.CRLF);
                set("configCode", StringUtil.valueOfZero(map.get("ccode")));
                set("code", StringUtil.valueOfZero(map.get("ccode")));
                // 處理内容
                parseBody(map);
                // 类结束 }
                javaStr.append(" }").append(IPubCons.CRLF);
                // 生成修改表脚本，
                FileUtilbc.write(new File(getClassPatch() + className + IPubCons.DOT_JAVA)
                        , StringUtil.toString(javaStr), PubEnvUtil.UTF_8);
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }


        public String parseConfig(String moduleType, String code) throws Exception
        {

            StringBuffer classNames = new StringBuffer();
            String sql = "SELECT * FROM sys_sqlconfig  sff WHERE ccode='" + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            // List< Map > mapList = Db.use().query(sql, Map.class);
            for (Map map : mapList)
            {
                javaStr = new StringBuffer();
                String className = StringUtil.firstCharUpperCase(StringUtil.valueOfZero(map.get("ccode")));
                // 處理头部
                parseHead(map, moduleType, className);
                // 处理构造函数
                javaStr.append("    public ").append(className).append("( ) { }");
                javaStr.append(IPubCons.CRLF).append(IPubCons.CRLF);
                set("configCode", StringUtil.valueOfZero(map.get("ccode")));
                set("code", StringUtil.valueOfZero(map.get("ccode")));
                // 處理内容
                parseBody(map);
                // 类结束 }
                javaStr.append(" }").append(IPubCons.CRLF);
                // 生成修改表脚本，
                FileUtilbc.write(new File(getClassPatch() + className + IPubCons.DOT_JAVA)
                        , StringUtil.toString(javaStr), PubEnvUtil.UTF_8);
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }

        public String parseList(String moduleType, String code) throws Exception
        {
            StringBuffer classNames = new StringBuffer();
            String sql = "SELECT * FROM sys_function_list  WHERE  sfl_code = '" + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            // List< Map > mapList = Db.use().query(sql, Map.class);
            for (Map map : mapList)
            {
                javaStr = new StringBuffer();
                String className = StringUtil.firstCharUpperCase(StringUtil.valueOfZero(map.get("sfl_code")));
                // 處理头部
                parseHead(map, moduleType, className);
                // 处理构造函数
                javaStr.append("    public ").append(className).append("( )").append(IPubCons.CRLF);
                javaStr.append("    {").append(IPubCons.CRLF);
                javaStr.append("        setColumns();").append(IPubCons.CRLF);
                javaStr.append("        setButtons();").append(IPubCons.CRLF);
                javaStr.append("    }").append(IPubCons.CRLF);

                set("ListCode", StringUtil.valueOfZero(map.get("sfl_code")));
                set("code", StringUtil.valueOfZero(map.get("sfl_code")));
                // 處理内容
                parseBody(map);
                // 处理子表
                sql = "SELECT * FROM sys_function_list_column WHERE sfl_id= '" + map.get("sfl_id") + "'";
                List< Map > childList = mapper.getDataBySql(sql);
                //    List< Map > childList = Db.use().query(sql, Map.class);
                parseChild(childList, "columns");
                sql = "SELECT * FROM sys_function_list_button WHERE sfl_id= '" + map.get("sfl_id") + "'";
                childList = mapper.getDataBySql(sql);
                //  childList = Db.use().query(sql, Map.class);
                parseChild(childList, "buttons");
                // 类结束 }
                javaStr.append(" }").append(IPubCons.CRLF);

                // 生成修改表脚本，
                FileUtilbc.write(new File(getClassPatch() + className + IPubCons.DOT_JAVA)
                        , StringUtil.toString(javaStr), PubEnvUtil.UTF_8);
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }


        public String parseForm(String moduleType, String code) throws Exception
        {

            StringBuffer classNames = new StringBuffer();
            String sql = "SELECT * FROM sys_function_form sff WHERE SFF_CODE='" + code + "'";
            List< Map > mapList = mapper.getDataBySql(sql);
            // List< Map > mapList = Db.use().query(sql, Map.class);
            for (Map map : mapList)
            {
                javaStr = new StringBuffer();
                String className = StringUtil.firstCharUpperCase(StringUtil.valueOfZero(map.get("sff_code")));
                // 處理头部
                parseHead(map, moduleType, className);
                // 处理构造函数
                javaStr.append("    public ").append(className).append("( )").append(IPubCons.CRLF)
                       .append("    {").append(IPubCons.CRLF)
                       .append("        setChildren();").append(IPubCons.CRLF)
                       // .append("        initPc_cntrol();").append(IPubCons.CRLF)
                       // .append("        initPc_cntrol();").append(IPubCons.CRLF)
                       .append("    }").append(IPubCons.CRLF);
                set("formCode", StringUtil.valueOfZero(map.get("sff_code")));
                set("code", StringUtil.valueOfZero(map.get("sff_code")));
                // 處理内容
                parseBody(map);
                sql = "SELECT * FROM sys_function_form_child WHERE SFF_ID= '"
                        + map.get("sff_id") + "' ORDER BY sff_type,sff_index ";
                List< Map > childList = mapper.getDataBySql(sql);
                // List< Map > childList = Db.use().query(sql, Map.class);

                // 处理控件信息
                // parseControl(childList);
                // 处理子表
                parseChild(childList, "children");

                // 类结束 }
                javaStr.append(" }").append(IPubCons.CRLF);
                // 生成修改表脚本，
                FileUtilbc.write(new File(getClassPatch() + className + IPubCons.DOT_JAVA)
                        , StringUtil.toString(javaStr), PubEnvUtil.UTF_8);
                classNames.append(className).append(IPubCons.DOT_JAVA).append(IPubCons._N);
            }
            if (classNames.length() > 0)
            { classNames.setLength(classNames.length() - 1); }

            return StringUtil.valueOfEmpty(classNames);
        }


        public void parseControl(List< Map > childList) throws Exception
        {
            if (PubEnvUtil.getSize(childList) > 0)
            {
                Map< String,List > groupListMap = CollectionUtil.receiveGroupListMap(childList, "sff_type", null);

                for (String key : groupListMap.keySet())
                {
                    String sff_type_temp = "";
                    String sfc_content_temp = "";

                    List list = groupListMap.get(key);
                    for (Object obj : list)
                    {
                        Map childMap = (Map) obj;
                        sff_type_temp = StringUtil.valueOfEmpty(childMap.get("sff_type"));
                        sfc_content_temp += StringUtil.valueOfEmpty(childMap.get("sfc_content"));
                    }
                    sfc_content_temp = URLDecoder.decode(sfc_content_temp, IPubCons.UTF_8)
                                                 .replace(IPubCons.TAB, IPubCons.SPACE);
                    parseControl(sff_type_temp, sfc_content_temp);
                }
            }
        }

        /************************************************************* <br>
         *
         *说明:
         * sff_type说明
         * 1.PC的布局    -- pc_layout     2.PC的控件    -- pc_cntrol
         * 3.app的布局   -- app_layout    4.app的控件   -- app_cntrol
         * 5.PC的配置查询 -- pc_cif_qry   6.PC的数据查询 -- pc_data_qry
         * ...
         * 10.app配置查询 -- app_cif_qry 11.app数据查询 -- app_data_qry
         * <br>
         *
         * @Description   <br>
         * @Date Created on 2022/9/8  15:59  <br>
         * @param sff_type
         * @param sfc_content <br>
         * @return void  <br>
         * @Author LIBENCHENG
         * @version 1.0 <br>
         ************************************************************* <br>
         */
        public void parseControl(String sff_type, String sfc_content) throws Exception
        {
            switch (sff_type)
            {
                case IPubCons.ONE:
                {
                    set("pc_layout", sfc_content.replace(PubEnvUtil.QUOTE, PubEnvUtil.SINGLE_QUOTE)
                                                .replace(IPubCons._N, "\" \n+ \"")
                                                .replace("\\", ""));
                    // parseChild((List) (JsonUtil.toMap(sfc_content).get("Controls")), "pc_layout");
                    break;
                }
                case IPubCons.TWO:
                {
                    parseChild((List) (JsonUtil.toMap(sfc_content).get("Controls")), "pc_cntrol");
                    break;
                }
                case IPubCons.THREE:
                {
                    set("app_layout", sfc_content.replace(PubEnvUtil.QUOTE, PubEnvUtil.SINGLE_QUOTE)
                                                 .replace(IPubCons._N, "\" \n+ \""));
                    break;
                }
                case IPubCons.FOUR:
                {
                    set("app_cntrol", JsonUtil.toMap(sfc_content));
                    break;
                }
                case IPubCons.FIVE:
                {
                    set("pc_cif_qry", (Map) (JsonUtil.toMap(sfc_content).get("config")));
                    break;
                }
                case IPubCons.SIX:
                {
                    set("pc_data_qry", (Map) (JsonUtil.toMap(sfc_content).get("config")));
                    break;
                }
                case IPubCons.TEN:
                {
                    set("app_cif_type", (Map) (JsonUtil.toMap(sfc_content).get("config")));
                    break;
                }
                case IPubCons.ELEVEN:
                {
                    set("app_data_type", (Map) (JsonUtil.toMap(sfc_content).get("config")));
                    break;
                }
                default:
            }

        }

        public void parseChild2(List childList, String initMethod) throws Exception
        {
            if (PubEnvUtil.equals("pc_cntrol", initMethod)
                    || PubEnvUtil.equals("app_cntrol", initMethod)
                    || PubEnvUtil.equals("columns", initMethod)
                    || PubEnvUtil.equals("buttons", initMethod))
            { javaStr.append("    /** 控件信息*/ ").append(IPubCons.CRLF); }
            else { javaStr.append("    /** 数据库原始数据*/").append(IPubCons.CRLF); }

            parseChildHead(initMethod);
            String att = initMethod + "Inner";
            String attUp = StringUtil.firstCharUpperCase(att);
            javaStr.append("        ").append(attUp).append(IPubCons.SPACE).append(att);
            javaStr.append(" = new ").append(attUp).append("( );").append(IPubCons.CRLF);

            StringBuffer internalStr = new StringBuffer();
            internalStr.append("   public class ");
            internalStr.append(StringUtil.firstCharUpperCase(initMethod)).append("Inner {");
            internalStr.append(IPubCons.CRLF).append(IPubCons.CRLF);
            javaStr.append("        // 这里可以使用反射获取数据。").append(IPubCons.CRLF);
            int size = PubEnvUtil.getSize(childList);
            for (int i = 0; i < PubEnvUtil.getSize(childList); i++)
            {
                Map childMap = (Map) childList.get(i);
                javaStr.append("        this.").append(initMethod);
                javaStr.append(".add(").append(att);
                javaStr.append(".get").append(i).append("());").append(IPubCons.CRLF);
                internalStr.append("        /** 获取数据方法").append(i).append("*/").append(IPubCons.CRLF);
                internalStr.append("        public HashMap< String,Object > get");
                internalStr.append(i).append("( ){").append(IPubCons.CRLF);
                internalStr.append("            HashMap< String,Object > temMap ");
                internalStr.append("= new HashMap< String,Object >();").append(IPubCons.CRLF);
                parseChildBody(internalStr, childMap);
                internalStr.append("            return temMap;");
                internalStr.append(IPubCons.CRLF).append("        }").append(IPubCons.CRLF);
            }
            internalStr.append("    }").append(IPubCons.CRLF);

            // javaStr.append("        for (int i = 0; i < ").append(size).append("; i++)").append(IPubCons.CRLF);
            // javaStr.append("        { this.").append(initMethod).append(".add(invoke(").append(att);
            // javaStr.append(", \"get\" + i)); }").append(IPubCons.CRLF);
            // 方法的括号
            javaStr.append("    }").append(IPubCons.CRLF).append(IPubCons.CRLF);
            javaStr.append(internalStr);
        }

        /************************************************************* <br>
         *
         *说明: 处理子表<br>
         *
         * @Description   <br>
         * @Date Created on 2022/9/7  18:12  <br>
         * @param childList <br>
         * @return void  <br>
         * @Author LIBENCHENG
         * @version 1.0 <br>
         ************************************************************* <br>
         */
        public void parseChild(List childList, String initMethod) throws Exception
        {
            // if (PubEnvUtil.equals("pc_cntrol", initMethod)
            //         || PubEnvUtil.equals("app_cntrol", initMethod)
            //         || PubEnvUtil.equals("columns", initMethod)
            //         || PubEnvUtil.equals("buttons", initMethod))
            // { javaStr.append("    /** 控件信息*/ ").append(IPubCons.CRLF); }
            // else { javaStr.append("    /**  数据库原始数据*/").append(IPubCons.CRLF); }

            parseChildHead(initMethod);
            // javaStr.append("        HashMap< String,Object >  temMap= new HashMap< String,Object >();")
            //        .append(IPubCons.CRLF);
            for (Object obj : childList)
            {
                Map childMap = (Map) obj;
                //特定字段解密
                // if (PubEnvUtil.isNotEmptyObj(childMap.get("SLC_QUERYLIST")))
                // {
                //     childMap.put("SLC_QUERYLIST",
                //                  URLDecoder.decode(StringUtil.valueOfEmpty(childMap.get("SLC_QUERYLIST")),
                //                                    IPubCons.UTF_8)
                //                            .replace(IPubCons.QUOTE, "\\\""));
                // }
                javaStr.append("        this.").append(initMethod).append(".add(\"")
                       .append(JSONObject.toJSONString(childMap)
                                         .replace(IPubCons.QUOTE, "'")
                                         // .replace(IPubCons.QUOTE, "\\\"")
                                         .replace(IPubCons._N, " \t\t+ \""))
                       .append("\");").append(IPubCons.CRLF);

                // // 使用hasn对象
                // javaStr.append("        temMap = new HashMap< String,Object >();")
                //        .append(IPubCons.CRLF);
                // parseChildBody(javaStr, childMap);
                // javaStr.append("        this.").append(initMethod).append(".add(temMap);")
                //        .append(IPubCons.CRLF).append(IPubCons.CRLF);
            }

            // 方法的括号
            javaStr.append("    }").append(IPubCons.CRLF);

        }

        public void parseChildBody(StringBuffer tempStr, Map childMap) throws Exception
        {
            for (Object key : childMap.keySet())
            { put(tempStr, key, childMap.get(key), Boolean.TRUE, Boolean.TRUE); }
        }

        private void put(StringBuffer tempStr, Object property, Object value, Boolean isMapStr, Boolean isXuYao) throws Exception
        {
            if (isMapStr)
            { tempStr.append("            temMap.put(\""); }
            else
            {
                tempStr.append("                put(\"");
                isXuYao = Boolean.TRUE;
            }
            tempStr.append(StringUtil.valueOfEmpty(property).replace("\\", IPubCons.EMPTY)).append("\", ");
            if (PubEnvUtil.equals("slc_querylist"
                    , StringUtil.valueOfEmpty(property).trim().toLowerCase()))
            {
                value = URLDecoder.decode(StringUtil.valueOfEmpty(value), IPubCons.UTF_8)
                                  .replace(IPubCons.QUOTE, "\\\"");
            }
            setAnonymous(tempStr, value, isXuYao);
            tempStr.append("").append(IPubCons.CRLF);
        }

        private void setAnonymous(StringBuffer tempStr, Object obj, Boolean isXuYao) throws Exception
        {
            if (obj instanceof List)
            {
                List cfigList = (List) obj;
                tempStr.append("new ArrayList()").append(IPubCons.CRLF);
                tempStr.append("                {{").append(IPubCons.CRLF);
                for (Object temp : cfigList)
                { setAnonymous(tempStr, temp, Boolean.FALSE); }
                tempStr.append(IPubCons.CRLF).append("            }});");
            }
            else if (obj instanceof Map)
            {
                Map tempMap = (Map) obj;
                tempStr.append("            new HashMap()").append(IPubCons.CRLF);
                tempStr.append("            {{").append(IPubCons.CRLF);
                for (Object key : tempMap.keySet())
                { put(tempStr, key, tempMap.get(key), Boolean.FALSE, Boolean.FALSE); }
                // tempStr.append("            }});");
                if (isXuYao) { tempStr.append("            }});"); }
                else { tempStr.append("            }};"); }
            }
            else
            {
                tempStr.append("\"")
                       .append(StringUtil.valueOfEmpty(obj)
                                         .replace(IPubCons.BACK_SLASH, IPubCons.EMPTY)
                                         .replace(IPubCons.QUOTE, IPubCons.BACK_SLASH + IPubCons.QUOTE))
                       .append("\");");
            }
        }


        /************************************************************* <br>
         *
         *说明: 處理内容<br>
         *
         * @Description   <br>
         * @Date Created on 2022/9/7  17:51  <br>
         * @return void  <br>
         * @Author LIBENCHENG
         * @version 1.0 <br>
         ************************************************************* <br>
         */
        public void parseBody(Map tableMap) throws Exception
        {
            for (Object key : tableMap.keySet())
            { set(key, tableMap.get(key)); }
        }

        private void set(Object property, Object obj) throws Exception
        {
            if (obj instanceof List)
            {
                List cfigList = (List) obj;
                javaStr.append(IPubCons.CRLF)
                       .append("    private ArrayList ")
                       .append(property).append(" = new ArrayList(){{");

                for (Object temp : cfigList)
                {
                    javaStr.append("        add(\"");
                    setAnonymous(javaStr, temp, Boolean.TRUE);
                    javaStr.append(");");
                }

                javaStr.append("    }};").append(IPubCons.CRLF).append(IPubCons.CRLF);
            }
            else if (obj instanceof Map)
            {
                Map cfigMap = (Map) obj;
                javaStr.append(IPubCons.CRLF).append("    private HashMap ")
                       .append(property)
                       .append(" = new HashMap(){{")
                       .append(IPubCons.CRLF);

                for (Object key : cfigMap.keySet())
                { put(javaStr, key, cfigMap.get(key), Boolean.FALSE, Boolean.TRUE); }

                javaStr.append("    }};").append(IPubCons.CRLF).append(IPubCons.CRLF);
            }
            else if (obj instanceof oracle.sql.NCLOB)
            {
                oracle.sql.NCLOB nclob = (oracle.sql.NCLOB) obj;
                String value = nclob.stringValue();
                // if (PubEnvUtil.equals("sfl_app_model_body"
                //         , StringUtil.toString(property).trim().toLowerCase()))
                // {
                //     value = URLDecoder.decode(nclob.stringValue(), IPubCons.UTF_8)
                //                       .replace(IPubCons.QUOTE, "\\\"");
                // }
                javaStr.append("    private String ")
                       .append(StringUtil.valueOfZero(property).toLowerCase())
                       .append(" = \"")
                       .append(value.replace(IPubCons._N, "\" \n            + \""))
                       .append("\";")
                       .append(IPubCons.CRLF);
            }
            else
            {
                javaStr.append("    private String ")
                       .append(StringUtil.valueOfZero(property).toLowerCase())
                       .append(" = \"")
                       .append(StringUtil.valueOfEmpty(obj))
                       .append("\";")
                       .append(IPubCons.CRLF);
            }
        }

        public void parseChildHead(String initMethod)
        {
            javaStr.append("    private ArrayList<String> ").append(initMethod).append(";\r\n\r\n");
            // parseChildHeadNote(initMethod);
            javaStr.append("   private void set").append(StringUtil.firstCharUpperCase(initMethod));
            javaStr.append("( )").append(IPubCons.CRLF).append("    {").append(IPubCons.CRLF);
            javaStr.append("        this.").append(initMethod).append(" = new ArrayList<String>();");
            javaStr.append(IPubCons.CRLF);

        }

        public void parseChildHeadNote(String initMethod)
        {
            javaStr.append("    /************************************************************* <br>\r\n");
            javaStr.append("     *").append(IPubCons.CRLF);
            javaStr.append("     *说明:  <br>").append(IPubCons.CRLF);
            if (PubEnvUtil.equals("children", initMethod))
            {
                javaStr.append("     *      sff_id[外键]、").append(IPubCons.CRLF);
                javaStr.append("     *      sfc_content[pc端对象]、").append(IPubCons.CRLF);
                javaStr.append("     *      sff_type[类型1pc端布局]、").append(IPubCons.CRLF);
                javaStr.append("     *      sff_index[排序]<br>").append(IPubCons.CRLF);
                javaStr.append("     *").append(IPubCons.CRLF);
                javaStr.append("     * @Description   <br>").append(IPubCons.CRLF);
                javaStr.append("     * @Date Created on ");
                javaStr.append(DateUtilbc.currentDateTime()).append(" <br>").append(IPubCons.CRLF);
                javaStr.append("     * @return void  <br>").append(IPubCons.CRLF);
                javaStr.append("     * @Author LIBENCHENG").append(IPubCons.CRLF);
                javaStr.append("     * @version 1.0 <br>").append(IPubCons.CRLF);
                javaStr.append("     ************************************************************* <br>")
                       .append(IPubCons.CRLF);
                javaStr.append("     */").append(IPubCons.CRLF);
            }
        }

        /************************************************************* <br>
         *
         *说明: 處理头部 <br>
         *
         * @Description   <br>
         * @Date Created on 2022/9/7  17:52  <br>
         * @param map <br>
         * @return void  <br>
         * @Author LIBENCHENG
         * @version 1.0 <br>
         ************************************************************* <br>
         */
        public void parseHead(Map map, String moduleType, String className)
        {

            javaStr.append("package com.xisoft.frame.entity.engine.");
            javaStr.append(moduleType).append(IPubCons.SEMICOLON).append(IPubCons.CRLF).append(IPubCons.CRLF);
            // javaStr.append("import com.xisoft.frame.entity.engine.base.EngineEntity;");
            // javaStr.append(IPubCons.CRLF).append(IPubCons.CRLF);
            javaStr.append("import java.io.Serializable;").append(IPubCons.CRLF);
            javaStr.append("import java.util.*;").append(IPubCons.CRLF).append(IPubCons.CRLF);
            javaStr.append("/**").append(IPubCons.CRLF);
            javaStr.append(" *").append(IPubCons.CRLF);
            javaStr.append(" * 说明：自动生成代码 ").append(IPubCons.CRLF);
            javaStr.append(" *       类型/名称 <=> ").append(moduleType);
            javaStr.append(IPubCons.SLASH);
            javaStr.append(StringUtil.valueOfEmpty(map.get("cnotice")));
            javaStr.append(StringUtil.valueOfEmpty(map.get("sff_name")));
            javaStr.append(StringUtil.valueOfEmpty(map.get("sfl_name")));
            javaStr.append(IPubCons.CRLF);
            // javaStr.append(" *@packagename: com.xisoft.frame.entity.engine<br>").append(IPubCons.CRLF);
            javaStr.append(" *@author: XIsoft <br>").append(IPubCons.CRLF);
            javaStr.append(" *@date: Created on ");
            javaStr.append(DateUtilbc.currentDateTime()).append(" <br>").append(IPubCons.CRLF);
            javaStr.append(" *@version 1.0 <br>").append(IPubCons.CRLF);
            javaStr.append(" */").append(IPubCons.CRLF);
            javaStr.append("@lombok.Data").append(IPubCons.CRLF);
            javaStr.append("@lombok.EqualsAndHashCode (callSuper = false)").append(IPubCons.CRLF);
            javaStr.append("public class ").append(className);

            if (PubEnvUtil.equals("list", moduleType))
            { javaStr.append(" extends com.xisoft.entity.config.table.Table"); }
            if (PubEnvUtil.equals("form", moduleType))
            { javaStr.append(" extends com.xisoft.entity.config.form.Form"); }
            // if (PubEnvUtil.equals("config", moduleType))
            // { javaStr.append(" extends com.xisoft.entity.config.form.Form"); }

            javaStr.append(IPubCons.CRLF).append("        implements Serializable, Cloneable");
            javaStr.append(" {").append(IPubCons.CRLF).append(IPubCons.CRLF);
            javaStr.append("    public static long serialVersionUID = 1L;");
            javaStr.append(IPubCons.CRLF).append(IPubCons.CRLF);

        }
    }
}
